import React, { useState, ReactElement } from 'react';
import './index.scss';
import TabItem from './TabItem';

export interface TabBarProps {
    activeKey?: string | number;
    defaultActiveKey?: string | number;
    children?: React.ReactNode;
    onChange?: (key: string | number) => void;
}

const defaultProps = {
}

const TabBar: React.FC<TabBarProps> & { Item: typeof TabItem } = (props) => {
    const {
        activeKey,
        defaultActiveKey,
        onChange,
        children,
        ...rest
    } = {
        ...defaultProps,
        ...props
    };

    let firstActiveKey: string | number;

    const items: ReactElement[] = [];
    

    React.Children.toArray(children).forEach((child, index) => { 
        if (!React.isValidElement(child)) {
            return;
        }
        const key = child.key || index;
        if(index === 0){
            firstActiveKey = key;
        }
        items.push(child);
    });

    const [activeTabKey, setActiveTabKey] = useState<string>();

    const handleClick = (key: string | number) => {
        console.log('handleClick', key);

        // setActiveTabKey(key);
        onChange?.(key);
    }

    return (
        <div className='seal-tab-bar'>
            <div className='seal-tab-bar__wrap'>
                {
                    items?.map((child, index) => {
                        const childProps = child.props;
                        if (!childProps) {
                            return;
                        }
                        const key = child.key || index;
                       
                        return (
                            <TabItem
                                key={key}
                                itemKey={key}
                                active={false}
                                style={childProps.style}
                                badge={childProps.badge}
                                title={childProps.title}
                                children={childProps.children}
                                onClick={handleClick}
                            />
                        )
                    })
                }
            </div>

        </div>
    )
}

TabBar.Item = TabItem;

export default TabBar;